"""Functions to handle the open files."""

#work around
import imp
fileHandler = imp.load_source('fileHandler', '.\\fileHandler.py')

import time
import thread
import os

# A dictionary in the form of fileno->fileHandler
openFiles = {}

def track_new_file(fileno, filename, username):
    global openFiles
    if fileno in openFiles:
        return openFiles[fileno]
    fileH = fileHandler.fileHandler(fileno, username, filename)
    openFiles[fileno] = fileH
    print "New file added: id %s %s\\%s" %(fileno, username, filename)
    return fileH

def check_timeout():
    """Peridoically checks when a file was last accessed
    removes the file"""
    global openFiles
    inactivity = 600
    timeout = 20
    
    while True:
        for fileN, fileH in openFiles.items():
            if time.time() - fileH.lastAccess > inactivity:
                print "%s has not been accessed in the last %d seconds" % (fileN, inactivity)
                openFiles.pop(fileN)
        time.sleep(timeout)

def get_file_info(fileno):
    """Retrieve information for a file"""
    global openFiles
    if fileno in openFiles:
        return openFiles[fileno]
    return None

def init_manager():
    thread.start_new_thread(check_timeout, ())
    os.chdir("..\\files\\")

if __name__ == "__main__":
    """Use this for testing purposes"""
    init_manager()
    track_new_file(3, "test", "sam")
    print openFiles
    
    print "main!!"
    
